<template>
  <div class="trade-page">
    <!-- 导航栏 -->
    <NavBar title="二手交易" />
    
    <!-- 搜索栏 -->
    <div class="search-section">
      <van-search
        v-model="searchKeyword"
        placeholder="搜索商品"
        @search="handleSearch"
      />
    </div>
    
    <!-- 商品列表 -->
    <div class="trade-list">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div
            v-for="item in tradeList"
            :key="item.tradeId"
            class="trade-item"
            @click="goToDetail(item.tradeId)"
          >
            <div class="trade-image">
              <img
                :src="item.pic1 || '/images/default-trade.png'"
                alt="商品图片"
                @error="handleImageError"
                @click="previewImage(getImageList(item), 0)"
              />
            </div>
            <div class="trade-info">
              <h3 class="trade-title">{{ item.title }}</h3>
              <p class="trade-desc">{{ item.description }}</p>
              <div class="trade-meta">
                <span class="trade-price">¥{{ item.price }}</span>
                <span class="trade-author">{{ item.nickName || '匿名用户' }}</span>
              </div>
              <div class="trade-time">
                {{ formatTime(item.createTimestamp) }}
              </div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>
    
    <!-- 发布按钮 -->
    <van-floating-bubble
      axis="xy"
      icon="plus"
      @click="goToAdd"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showImagePreview } from 'vant'
import NavBar from '@/components/Common/NavBar.vue'
import { tradeApi, type TradeItem } from '@/api/trade'
import { formatTime } from '@/utils/format'

const router = useRouter()

const tradeList = ref<TradeItem[]>([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const searchKeyword = ref('')
const pageNo = ref(0)
const pageSize = 10

// 加载数据
const loadData = async (isRefresh = false) => {
  try {
    const params = {
      pageNo: isRefresh ? 0 : pageNo.value,
      pageSize,
      str: searchKeyword.value || undefined
    }
    
    const result = await tradeApi.getList(params)
    
    if (result.code === 1) {
      const newData = result.data.records || []
      
      if (isRefresh) {
        tradeList.value = newData
        pageNo.value = 0
      } else {
        tradeList.value.push(...newData)
      }
      
      // 检查是否还有更多数据
      finished.value = newData.length < pageSize
      
      if (!isRefresh) {
        pageNo.value++
      }
    } else {
      showToast(result.msg || '加载失败')
    }
  } catch (error) {
    console.error('加载二手交易数据失败:', error)
    showToast('加载失败')
  }
}

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true
  finished.value = false
  await loadData(true)
  refreshing.value = false
}

// 上拉加载
const onLoad = async () => {
  if (finished.value) return
  loading.value = true
  await loadData()
  loading.value = false
}

// 搜索
const handleSearch = async () => {
  pageNo.value = 0
  finished.value = false
  await loadData(true)
}

// 检查是否有图片
const hasImages = (item: any) => {
  return item.pic1 || item.pic2 || item.pic3
}

// 获取图片列表
const getImageList = (item: any) => {
  const images = []
  if (item.pic1) images.push(item.pic1)
  if (item.pic2) images.push(item.pic2)
  if (item.pic3) images.push(item.pic3)
  return images
}

// 图片预览
const previewImage = (images: string[], index: number) => {
  showImagePreview({
    images,
    startPosition: index,
    closeable: true
  })
}

// 图片加载失败处理
const handleImageError = (e: Event) => {
  const target = e.target as HTMLImageElement
  target.src = '/images/default-trade.png'
}

// 跳转到详情页
const goToDetail = (tradeId: string) => {
  router.push(`/trade/detail/${tradeId}`)
}

// 跳转到发布页
const goToAdd = () => {
  router.push('/trade/add')
}

onMounted(() => {
  loadData(true)
})
</script>

<style scoped>
.trade-page {
  min-height: 100vh;
  background-color: #f1f1f1;
  padding-bottom: 60px;
}

.search-section {
  padding: 12px 16px;
  background: white;
  border-bottom: 1px solid #eee;
}

.trade-list {
  padding: 8px 16px;
}

.trade-item {
  display: flex;
  background: white;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s;
}

.trade-item:hover {
  transform: translateY(-2px);
}

.trade-image {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  overflow: hidden;
  margin-right: 12px;
  flex-shrink: 0;
}

.trade-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.trade-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.trade-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.trade-desc {
  font-size: 14px;
  color: #666;
  margin: 0 0 8px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.trade-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.trade-price {
  font-size: 18px;
  font-weight: 600;
  color: #ff4444;
}

.trade-author {
  font-size: 12px;
  color: #999;
}

.trade-time {
  font-size: 12px;
  color: #999;
  margin-top: auto;
}
</style>